//
//  SPVoiceManager.m
//  QADoctor
//
//  Created by 陈飞宇 on 17/3/30.
//  Copyright © 2017年 Spencer. All rights reserved.
//

#import "SPVoiceManager.h"
@interface SPVoiceManager ()
@property (nonatomic,strong)AVAudioPlayer *avplay;
@end
@implementation SPVoiceManager
+ (instancetype)defaultManager
{
    static SPVoiceManager *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)playingMusicUrl:(NSURL *)url
{

    //在播放的时候 再次点击就暂停当前的录音的播放
 
 
    self.avplay = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    
    
    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
                            sizeof(sessionCategory),
                            &sessionCategory);
    
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                             sizeof (audioRouteOverride),
                             &audioRouteOverride);
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //默认情况下扬声器播放
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(sensorStateChange:)
     name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
    
    
     [self.avplay play];
        
        //根据是否插入耳机  决定是否是扬声器或者耳机播放
        NSError *setCategoryError = nil;
        if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                              withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                                    error:&setCategoryError]) {
        }
        

}


//处理监听触发事件
-(void)sensorStateChange:(NSNotificationCenter *)notification;
{
    //如果此时手机靠近面部放在耳朵旁，那么声音将通过听筒输出，并将屏幕变暗（省电啊）
    if ([[UIDevice currentDevice] proximityState] == YES)
    {
        NSLog(@"Device is close to user");
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    }
    else
    {
        NSLog(@"Device is not close to user");
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    }
}
- (void)stop
{
    [self.avplay stop];
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
}
- (BOOL)isPlaying
{
    return [self.avplay isPlaying]?YES:NO;
}
@end
